package gitobject;

import repository.Repository;
import zlib.ZLibUtils;
import java.io.*;

public class GitObject implements Serializable{

    protected String fmt;                  //type of object
    protected String key;                  //key of object
    protected String mode;                 //mode of object
    protected static String path;          //absolute path of objects

    static {
        try {
            path = Repository.getGitDir() + File.separator + "objects";
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected String value;                //value of object
    protected long modified_time;

    public String getFmt() {
        return fmt;
    }

    public String getKey() {
        return key;
    }

    public long getTime() {
        return modified_time;
    }
    public String getMode() {
        return mode;
    }

    public static String getPath() {
        return path;
    }

    public String getValue() {
        return value;
    }


    public GitObject() {
    }

    /**
     * Get the value(content) of file
     *
     * @param file
     * @return String
     * @throws IOException
     */
    public static String getValue(File file) throws IOException {
        /* Todo: Add your code here
         *   You should delete the return statement below before coding.  */
//        Scanner read = new Scanner(file);
//        StringBuilder result = new StringBuilder();
//        while (read.hasNext()) {
//            result.append(read.nextLine());
//            result.append(System.getProperty("line.separator"));
//        }
//        return result.toString();
        FileInputStream fis = new FileInputStream(file);
        byte[] content = fis.readAllBytes();
        fis.close();
        return new String(content);
    }

    /**
     * Todo: Serialize the object to the local repository.
     *
     * @throws Exception
     */
    public void writeObject() throws Exception {
        /**
         * Add your code here.
         */
        String store_path = path + File.separator + key;
        ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(store_path));
        output.writeObject(this);
        output.close();
    }

    /**
     * Todo: Serialize the object and compress with zlib.
     *
     * @throws Exception
     */
    public void compressWrite() throws Exception {
        /**
         * Add your code here.
         */
        String store_path = path + File.separator + key;
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bao);
        oos.writeObject(this);
        oos.close();
        byte[] data = bao.toByteArray();
        bao.close();
        FileOutputStream fos = new FileOutputStream(store_path);
        ZLibUtils.compress(data, fos);
        fos.close();
    }
}
